// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 获取轮播图数据
    const bannersPromise = db.collection('banners')
      .where({
        status: 'active'
      })
      .orderBy('order', 'asc')
      .get()

    // 获取分类数据
    const categoriesPromise = db.collection('categories')
      .where({
        parentId: null // 获取一级分类
      })
      .orderBy('order', 'asc')
      .limit(10)
      .get()

    // 获取新品上市
    const newProductsPromise = db.collection('products')
      .where({
        isNew: true,
        status: 'on'
      })
      .orderBy('createdAt', 'desc')
      .limit(10)
      .get()

    // 获取特价优惠
    const specialOffersPromise = db.collection('products')
      .where({
        isSpecial: true,
        status: 'on'
      })
      .orderBy('specialPrice', 'asc')
      .limit(4)
      .get()

    // 获取秒杀商品
    const seckillProductsPromise = db.collection('products')
      .where({
        isSeckill: true,
        status: 'on'
      })
      .limit(6)
      .get()

    // 获取人气热卖
    const hotProductsPromise = db.collection('products')
      .where({
        isHot: true,
        status: 'on'
      })
      .orderBy('soldCount', 'desc')
      .limit(4)
      .get()

    // 获取优惠券
    const couponsPromise = db.collection('coupons')
      .where({
        status: 'active'
      })
      .limit(3)
      .get()

    // 并行请求数据
    const [
      bannersResult,
      categoriesResult,
      newProductsResult,
      specialOffersResult,
      seckillProductsResult,
      hotProductsResult,
      couponsResult
    ] = await Promise.all([
      bannersPromise,
      categoriesPromise,
      newProductsPromise,
      specialOffersPromise,
      seckillProductsPromise,
      hotProductsPromise,
      couponsPromise
    ])

    // 处理秒杀商品数据，计算已售百分比
    const seckillProducts = seckillProductsResult.data.map(product => {
      // 计算已售百分比
      const soldPercentage = Math.floor((product.soldCount / product.totalStock) * 100)
      return {
        ...product,
        soldPercentage
      }
    })

    // 如果有用户信息，检查用户已领取的优惠券
    let userCoupons = []
    if (event.userId) {
      userCoupons = await db.collection('userCoupons')
        .where({
          userId: event.userId,
          status: 'unused'
        })
        .get()
        .then(res => res.data.map(item => item.couponId))
    }

    // 标记已领取的优惠券
    const coupons = couponsResult.data.map(coupon => ({
      ...coupon,
      isClaimed: userCoupons.includes(coupon._id)
    }))

    // 返回所有数据
    return {
      success: true,
      data: {
        banners: bannersResult.data,
        categories: categoriesResult.data,
        newProducts: newProductsResult.data,
        specialOffers: specialOffersResult.data,
        seckillProducts,
        hotProducts: hotProductsResult.data,
        coupons
      }
    }
  } catch (error) {
    console.error(error)
    return {
      success: false,
      message: error.message
    }
  }
}